import { reactive, computed, ref, watch, unref, watchEffect } from 'vue';
import { defineStore } from 'pinia'
import { useEventListener, useSessionStorage } from '@vueuse/core';


export interface KeepCache {
  keepAliveViews: string[]; // 页面缓存
  // nokeepAliveViews: string[] 
  keepAliveTabs: string[]; // tabs 缓存
  keepAliveBreadcrumbs: string[]; // 面包屑缓存
}

export type KeepCacheType = "view" | "tabs" | "crumb"

// 页面缓存
export const useKeepLiveStore = defineStore('viewCaches', () => {
  const isCache = eval(import.meta.env.VITE_APP_KEEPLIVE)

  let keepActiveTab = useSessionStorage("th-keep-active-tab", "") // 当前活跃的routeName， 此处建立

  const cache = reactive<KeepCache>({
    keepAliveViews: [],
    keepAliveTabs: [],
    keepAliveBreadcrumbs: [],
  })


  const cacheType: Record<KeepCacheType, string[]> = {
    view: cache.keepAliveViews,
    tabs: cache.keepAliveTabs,
    crumb: cache.keepAliveBreadcrumbs,
  }

  // 建立tab道面包屑的映射关系，方便缓存
  const tabToBreadcrumbsMapping = ref<Record<string, string[]>>({})
  const tabToBreadcrumbsMappingKeepLive = computed(()=>{
    return Object.values(tabToBreadcrumbsMapping.value).reduce((pre,next)=> [...pre,...next] , [])
  })
  
  // tab下面存在的面包屑缓存起来
  watch(cache.keepAliveBreadcrumbs, (crumbs) => {
    const crumbsBack = [...crumbs]
    if (keepActiveTab.value === "") return
    tabToBreadcrumbsMapping.value[keepActiveTab.value] = crumbsBack
  },
    {
      immediate: true
    })

  // 新增keep alive 缓存页面
  const addKeepAlive = (routerName: string, type: KeepCacheType = "view") => {
    if (type === "tabs") {
      keepActiveTab.value = routerName
    }
    const cacheIndex = cacheType[type].indexOf(routerName)
    if (cacheIndex > -1) return
    cacheType[type].push(routerName)
  }

  // 删除keep alive 缓存页面
  const removeKeepAlive = (routerName: string, type: KeepCacheType = "view") => {
    const cacheIndex = cacheType[type].indexOf(routerName)
    if (cacheIndex > -1) {
      cacheType[type].splice(cacheIndex, 1)
    }
  }

  // 清空keeplive 缓存页面
  function clearKeepLive(type: KeepCacheType = "view") {
    cacheType[type].length = 0
  }

  return {
    isCache,
    cache: isCache ? cache : {
      keepAliveViews: [],
      keepAliveTabs: [],
      keepAliveBreadcrumbs: [],
    },
    caches: isCache ? computed<string[]>(() => ([...cache.keepAliveViews, ...cache.keepAliveTabs, ...cache.keepAliveBreadcrumbs, ...tabToBreadcrumbsMappingKeepLive.value])) : [],
    tabToBreadcrumbsMapping,
    addKeepAlive,
    removeKeepAlive,
    clearKeepLive
  }
})
